<template>
    <div class="cutting-diagram">
        <button class="copy-btn" @click="copyData" title="复制切割数据">
            <span class="icon">📋</span>
            复制数据
        </button>
        
        <div class="dimension-info top">
            <div class="size-detail">
                <span class="total-size">总宽: {{ material.width }}mm</span>
                <span class="unit-size">单块: {{ isHorizontal ? target.width : target.height }}mm × {{ cuts.x }}块</span>
                <span class="remaining" :class="{ 'warning': isWidthRemainSmall }">
                    余: {{ widthRemaining }}mm
                </span>
                <button class="reduce-btn" @click="reduceColumns" :disabled="!canReduceColumns">
                    -1列
                </button>
            </div>
        </div>
        <div class="diagram-container">
            <div class="dimension-info left">
                <div class="size-detail vertical">
                    <span class="total-size">总高: {{ material.height }}mm</span>
                    <span class="unit-size">单块: {{ isHorizontal ? target.height : target.width }}mm × {{ cuts.y }}块</span>
                    <span class="remaining" :class="{ 'warning': isHeightRemainSmall }">
                        余: {{ heightRemaining }}mm
                    </span>
                    <button class="reduce-btn vertical" @click="reduceRows" :disabled="!canReduceRows">
                        -1行
                    </button>
                </div>
            </div>
            <div class="material" 
                :style="materialStyle"
                @mousedown.prevent="startSelection"
                @mouseup="endSelection"
                @mouseleave="endSelection">
                <template v-if="selectedAreaInfo">
                    <div class="reference-line vertical left"
                        :style="{
                            left: `${getReferenceLinePosition('vertical')}%`,
                            height: '100%'
                        }">
                        <span class="reference-label">
                            {{ selectedAreaInfo.width }}mm
                        </span>
                    </div>
                    <div class="reference-line vertical right"
                        v-if="!isSecondLineOverflow('vertical')"
                        :style="{
                            left: `${getReferenceLinePosition('vertical') * 2}%`,
                            height: '100%'
                        }">
                    </div>
                    <div class="reference-line vertical right"
                        v-if="!isThirdLineOverflow('vertical')"
                        :style="{
                            left: `${getReferenceLinePosition('vertical') * 3}%`,
                            height: '100%'
                        }">
                    </div>
                    <div class="reference-line vertical right"
                        v-if="!isFourthLineOverflow('vertical')"
                        :style="{
                            left: `${getReferenceLinePosition('vertical') * 4}%`,
                            height: '100%'
                        }">
                    </div>
                    <div class="reference-line vertical right"
                        v-if="!isFiveLineOverflow('vertical')"
                        :style="{
                            left: `${getReferenceLinePosition('vertical') * 5}%`,
                            height: '100%'
                        }">
                    </div>
                    <div class="reference-line vertical right"
                        v-if="!isSixLineOverflow('vertical')"
                        :style="{
                            left: `${getReferenceLinePosition('vertical') * 6}%`,
                            height: '100%'
                        }">
                    </div>
                    <div class="reference-line horizontal top"
                        :style="{
                            top: `${getReferenceLinePosition('horizontal')}%`,
                            width: '100%'
                        }">
                        <span class="reference-label">
                            {{ selectedAreaInfo.height }}mm
                        </span>
                    </div>
                    <div class="reference-line horizontal bottom"
                        v-if="!isSecondLineOverflow('horizontal')"
                        :style="{
                            top: `${getReferenceLinePosition('horizontal') * 2}%`,
                            width: '100%'
                        }">
                    </div>
                    <div class="reference-line horizontal bottom"
                        v-if="!isThirdLineOverflow('horizontal')"
                        :style="{
                            top: `${getReferenceLinePosition('horizontal') * 3}%`,
                            width: '100%'
                        }">
                    </div>
                    <div class="reference-line horizontal bottom"
                        v-if="!isFourthLineOverflow('horizontal')"
                        :style="{
                            top: `${getReferenceLinePosition('horizontal') * 4}%`,
                            width: '100%'
                        }">
                    </div>
                    <div class="reference-line horizontal bottom"
                        v-if="!isFiveLineOverflow('horizontal')"
                        :style="{
                            top: `${getReferenceLinePosition('horizontal') * 5}%`,
                            width: '100%'
                        }">
                    </div>
                    <div class="reference-line horizontal bottom"
                        v-if="!isSixLineOverflow('horizontal')"
                        :style="{
                            top: `${getReferenceLinePosition('horizontal') * 6}%`,
                            width: '100%'
                        }">
                    </div>
                </template>
                <div v-if="selectedAreaInfo" class="selected-area-info">
                    <div class="area-size">
                        {{ selectedAreaInfo.width }}×{{ selectedAreaInfo.height }}
                        ({{ selectedAreaInfo.cols }}×{{ selectedAreaInfo.rows }})
                    </div>
                </div>
                <div class="grid-info">
                    <div class="cut-details">
                        <span class="cut-count">{{ cuts.x }}×{{ cuts.y }}={{ cuts.x * cuts.y }}</span>
                        <!-- <span class="direction">{{ isHorizontal ? '顺向' : '逆向' }}</span>
                        <span class="efficiency">利用率: {{ efficiency.toFixed(1) }}%</span> -->
                    </div>
                </div>
                <div v-for="row in cuts.y" :key="`row-${row}`" class="cut-row">
                    <div v-for="col in cuts.x" :key="`col-${col}`"
                        class="cut-block"
                        :class="{ 
                            'selected': isBlockSelected(row-1, col-1),
                            'deselecting': isDeselecting && isBlockSelected(row-1, col-1)
                        }"
                        @mouseenter="handleBlockHover(row-1, col-1)"
                        @mousedown.stop.prevent="handleBlockMouseDown(row-1, col-1)">
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';

const props = defineProps<{
  material: { width: number; height: number };
  target: { width: number; height: number };
  cuts: { x: number; y: number };
  isHorizontal: boolean;
    selectedBlocks: { row: number; col: number }[];
}>();

const emit = defineEmits<{
    (e: 'block-select', position: { row: number; col: number }): void;
    (e: 'update:cuts', cuts: { x: number; y: number }): void;
}>();

// 添加状态变量
const isSelecting = ref(false);
const selectionMode = ref<'select' | 'deselect'>('select');

const materialStyle = computed(() => {
    const scale = Math.min(600 / props.material.width, 400 / props.material.height);
    return {
        width: `${props.material.width * scale}px`,
        height: `${props.material.height * scale}px`,
    };
});

const isBlockSelected = (row: number, col: number) => {
    return props.selectedBlocks.some(block => 
        block.row === row && block.col === col
    );
};

// 添加取消选择状态
const isDeselecting = computed(() => isSelecting.value && selectionMode.value === 'deselect');

// 修改开始选择函数
const startSelection = () => {
    isSelecting.value = true;
};

// 修改结束选择函数
const endSelection = () => {
    isSelecting.value = false;
    selectionMode.value = 'select'; // 重置选择模式
};

// 修改方块鼠标按下事件处理
const handleBlockMouseDown = (row: number, col: number) => {
    isSelecting.value = true;
    // 设置选择模式
    selectionMode.value = isBlockSelected(row, col) ? 'deselect' : 'select';
    handleBlockSelection(row, col);
};

// 修改方块悬停事件处理
const handleBlockHover = (row: number, col: number) => {
    if (!isSelecting.value) return;
    handleBlockSelection(row, col);
};

// 处理方块选择
const handleBlockSelection = (row: number, col: number) => {
    const isSelected = isBlockSelected(row, col);
    
    // 如果是选择模式且方块未选中，或是取消模式且方块已选中
    if ((selectionMode.value === 'select' && !isSelected) || 
        (selectionMode.value === 'deselect' && isSelected)) {
        emit('block-select', { row, col });
    }
};

// 修改剩余尺寸的计算方式
const widthRemaining = computed(() => {
    if (props.isHorizontal) {
        return props.material.width - (props.target.width * props.cuts.x);
    } else {
        return props.material.width - (props.target.height * props.cuts.x);
    }
});

const heightRemaining = computed(() => {
    if (props.isHorizontal) {
        return props.material.height - (props.target.height * props.cuts.y);
    } else {
        return props.material.height - (props.target.width * props.cuts.y);
    }
});

// 修改剩余尺寸的警告阈值
const isWidthRemainSmall = computed(() => {
    return widthRemaining.value > 0 && widthRemaining.value < 20;
});

const isHeightRemainSmall = computed(() => {
    return heightRemaining.value > 0 && heightRemaining.value < 20;
});

// const efficiency = computed(() => {
//     const materialArea = props.material.width * props.material.height;
//     const usedArea = props.target.width * props.target.height * props.cuts.x * props.cuts.y;
//     return (usedArea / materialArea) * 100;
// });

// 添加选中区域信息的计算属性
const selectedAreaInfo = computed(() => {
    if (props.selectedBlocks.length === 0) return null;

    // 获取选中方块的行列信息
    const rows = props.selectedBlocks.map(block => block.row);
    const cols = props.selectedBlocks.map(block => block.col);

    // 计算选中区域的范围
    const minRow = Math.min(...rows);
    const maxRow = Math.max(...rows);
    const minCol = Math.min(...cols);
    const maxCol = Math.max(...cols);

    // 计算选中区域的行数和列数
    const rowCount = maxRow - minRow + 1;
    const colCount = maxCol - minCol + 1;

    // 计算选中区域的实际尺寸
    const width = props.isHorizontal 
        ? props.target.width * colCount 
        : props.target.height * colCount;
    const height = props.isHorizontal 
        ? props.target.height * rowCount 
        : props.target.width * rowCount;

    return {
        width,
        height,
        rows: rowCount,
        cols: colCount
    };
});

// 添加参考线位置计算方法
const getReferenceLinePosition = (direction: 'vertical' | 'horizontal') => {
    if (!selectedAreaInfo.value) return 0;

    const rows = props.selectedBlocks.map(block => block.row);
    const cols = props.selectedBlocks.map(block => block.col);
    const maxRow = Math.max(...rows);
    const maxCol = Math.max(...cols);

    if (direction === 'vertical') {
        return ((maxCol + 1) / props.cuts.x) * 100;
    } else {
        return ((maxRow + 1) / props.cuts.y) * 100;
    }
};

// 添加溢出检查方法
const isSecondLineOverflow = (direction: 'vertical' | 'horizontal') => {
    if (!selectedAreaInfo.value) return true;
    
    const position = getReferenceLinePosition(direction) * 2;
    return position > 100;
};

const isThirdLineOverflow = (direction: 'vertical' | 'horizontal') => {
    if (!selectedAreaInfo.value) return true;
    
    const position = getReferenceLinePosition(direction) * 3;
    return position > 100;
};

const isFourthLineOverflow = (direction: 'vertical' | 'horizontal') => {
    if (!selectedAreaInfo.value) return true;
    
    const position = getReferenceLinePosition(direction) * 4;
    return position > 100;
};
const isFiveLineOverflow = (direction: 'vertical' | 'horizontal') => {
    if (!selectedAreaInfo.value) return true;
    
    const position = getReferenceLinePosition(direction) * 5;
    return position > 100;
};
const isSixLineOverflow = (direction: 'vertical' | 'horizontal') => {
    if (!selectedAreaInfo.value) return true;
    
    const position = getReferenceLinePosition(direction) * 6;
    return position > 100;
};

// 检查是否可以减少行数和列数
const canReduceColumns = computed(() => props.cuts.x > 1);
const canReduceRows = computed(() => props.cuts.y > 1);

// 减少列数方法
const reduceColumns = () => {
    if (canReduceColumns.value) {
        emit('update:cuts', { 
            x: props.cuts.x - 1, 
            y: props.cuts.y 
        });
        // 清除超出新范围的选中方块
        props.selectedBlocks.forEach(block => {
            if (block.col >= props.cuts.x - 1) {
                emit('block-select', block);
            }
        });
    }
};

// 减少行数方法
const reduceRows = () => {
    if (canReduceRows.value) {
        emit('update:cuts', { 
            x: props.cuts.x, 
            y: props.cuts.y - 1 
        });
        // 清除超出新范围的选中方块
        props.selectedBlocks.forEach(block => {
            if (block.row >= props.cuts.y - 1) {
                emit('block-select', block);
            }
        });
    }
};

// 简化复制方法
const copyData = async () => {
    try {
        // 准备文本数据
        const textData = [
            props.material.width,
            props.material.height,
            props.target.width,
            props.target.height,
            props.cuts.x,
            props.cuts.y,
            props.cuts.x * props.cuts.y,
        ];

        if (selectedAreaInfo.value) {
            textData.push(
                selectedAreaInfo.value.width,
                selectedAreaInfo.value.height,
                selectedAreaInfo.value.cols,
                selectedAreaInfo.value.rows
            );
        }

        await navigator.clipboard.writeText(textData.join(','));
        alert('已复制数据到剪贴板！');
    } catch (err) {
        console.error('复制失败:', err);
        alert('复制失败，请重试');
    }
};
</script>

<style scoped>
.cutting-diagram {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 2rem;
    position: relative; /* 确保复制按钮定位正确 */
}

.diagram-container {
    display: flex;
    align-items: center;
    position: relative;
}

.dimension-info {
    font-size: 0.75em;
    color: #475569;
    padding: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
}

.dimension-info.top {
    margin-bottom: 0.5rem;
}

.dimension-info.left {
    writing-mode: vertical-rl;
    transform: rotate(180deg);
    margin-right: 0.5rem;
}

.size-detail {
    display: flex;
    gap: 1rem;
    align-items: center;
    background-color: #f8fafc;
    padding: 0.25rem 0.75rem;
    border-radius: 4px;
    border: 1px solid #e2e8f0;
}

.size-detail.vertical {
    /* flex-direction: column; */
    gap: 0.5rem;
    writing-mode: vertical-rl;
    transform: rotate(180deg);
}

.total-size {
    font-weight: 500;
    color: #1e293b;
}

.unit-size {
    color: #475569;
}

.remaining {
    color: #475569;
}

.remaining.warning {
    color: #dc2626;
    font-weight: 500;
}

.cut-details {
    display: flex;
    gap: 0.75rem;
    align-items: center;
}

.cut-count {
    font-weight: 500;
}

.direction {
    padding: 0.1rem 0.3rem;
    border-radius: 3px;
    font-size: 0.7em;
    background-color: #dbeafe;
    color: #1e40af;
}

.efficiency {
    color: #059669;
    font-weight: 500;
}

.grid-info {
    position: absolute;
    top: -1rem;
    right: -3rem;
    font-size: 0.75em;
    background-color: #f8fafc;
    padding: 0.25rem 0.75rem;
    border-radius: 4px;
    border: 1px solid #e2e8f0;
    white-space: nowrap;
}

.material {
    border: 2px solid #334155;
    display: flex;
    flex-direction: column;
    user-select: none; /* 防止拖动时选中文本 */
    cursor: default;
    position: relative; /* 确保可以正确定位选中区域信息 */
}

.material:active {
    cursor: grabbing;
}

.cut-row {
    display: flex;
    flex: 1;
}

.cut-block {
    flex: 1;
    border: 1px solid #94a3b8;
    cursor: pointer;
    transition: all 0.15s ease-out; /* 加快过渡动画速度 */
}

.cut-block:hover {
    background-color: rgba(59, 130, 246, 0.1);
}

.cut-block.selected {
    background-color: rgba(59, 130, 246, 0.2);
    border-color: #3b82f6;
}

/* 添加取消选择状态的样式 */
.cut-block.deselecting {
    background-color: rgba(239, 68, 68, 0.1);
    border-color: #ef4444;
}

.selected-area-info {
    position: absolute;
    top: -1rem;
    left: -2rem;
    transform: translate(-50%, -50%);
    z-index: 10;
    pointer-events: none; /* 防止干扰方块的选择 */
}

.area-size {
    background-color: rgba(255, 255, 255, 0.9);
    border: 1px solid #3b82f6;
    border-radius: 4px;
    padding: 0.25rem 0.5rem;
    font-size: 0.75em;
    color: #3b4657;
    font-weight: 500;
    white-space: nowrap;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.reference-line {
    position: absolute;
    pointer-events: none;
    z-index: 5;
    opacity: 0.8; /* 降低透明度，使视觉效果更柔和 */
    transition: opacity 0.2s ease;
}

.reference-line:hover {
    opacity: 1;
}

.reference-line.vertical {
    border-left: 2px dashed #ff0000;
}

.reference-line.horizontal {
    border-top: 2px dashed #ff0000;
}

.reference-line.vertical.left .reference-label {
    transform: translateX(4px);
    top: 4px;
}

.reference-line.vertical.right .reference-label {
    transform: translateX(4px);
    bottom: 4px;
}

.reference-line.horizontal.top .reference-label {
    transform: translateY(-24px) translateX(-4px);
}

.reference-line.horizontal.bottom .reference-label {
    transform: translateY(4px) translateX(-4px);
}

.reference-label {
    background-color: #3b82f6;
    color: white;
    font-size: 0.7em;
    padding: 2px 4px;
    border-radius: 2px;
    position: absolute;
    white-space: nowrap;
}

.reduce-btn {
    background-color: #ef4444;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 2px 6px;
    font-size: 0.7em;
    cursor: pointer;
    transition: all 0.2s;
    margin-left: 8px;
}

.reduce-btn:hover:not(:disabled) {
    background-color: #dc2626;
}

.reduce-btn:disabled {
    background-color: #cbd5e1;
    cursor: not-allowed;
}

.reduce-btn.vertical {
    writing-mode: horizontal-tb;
    transform: none;
    margin-left: 0;
    margin-top: 8px;
}

.copy-btn {
    position: absolute;
    top: 1rem;
    right: 1rem;
    background-color: #2563eb;
    color: white;
    border: none;
  border-radius: 4px;
    padding: 0.5rem 1rem;
    font-size: 0.75em;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    transition: all 0.2s;
    box-shadow: 0 2px 4px rgba(37, 99, 235, 0.2);
}

.copy-btn:hover {
    background-color: #1d4ed8;
    transform: translateY(-1px);
    box-shadow: 0 4px 6px rgba(37, 99, 235, 0.3);
}

.copy-btn .icon {
    font-size: 1.1em;
}
</style>